use actix_web::{App, HttpResponse, Responder, ResponseError, web};
use crate::states::*;

use rand::Rng;
use crate::db_access::course::*;
use crate::error::MyError;
use crate::models::course::Course;


pub async fn add_course(new_course: web::Json<Course>, data: web::Data<AppState>) -> HttpResponse {
    println!("---------------------add_course---------------");

    let res = add_course_db(&data.db, new_course.into()).await;


    HttpResponse::Ok().json("success!")
}


pub async fn get_course_by_teacher(data: web::Data<AppState>, params: web::Path<usize, >) -> Result<HttpResponse, MyError> {
    let teacher_id = i32::try_from(params.into_inner()).unwrap();

    get_course_by_teacher_id_db(&data.db, teacher_id)
        .await
        .map(|c| HttpResponse::Ok().json(c))
}


pub async fn get_course_detail(data: web::Data<AppState>, params: web::Path<(usize)>)
                               -> Result<HttpResponse, MyError> {
    let course_id = i32::try_from(params.into_inner()).unwrap();
    get_course_detail_db(&data.db, course_id)
        .await
        .map(|c| HttpResponse::Ok().json(c))
}